<template>
  <div class="modal">
    <div class="mask" @click="changeIsShowModal(false)"></div>
    <div class="loginbox">
      <div class="close" @click="changeIsShowModal(false)">
        <img src="../assets/img/close.png" alt="" />
      </div>

      <section class="nav">
        <a
          href="#"
          @click="isShowContent = true"
          :class="{ active: isShowContent }"
          >手机号码登录</a
        >
        <a> | </a>
        <a href="#" @click="showQR" :class="{ active: !isShowContent }"
          >微信扫码登录</a
        >
      </section>
      <div class="content">
        <div class="phoneLogin" v-show="isShowContent">
          <div class="row">
            <input
              type="text"
              placeholder="请输入手机号"
              class="ipt"
              v-model="phoneNumber"
            />
          </div>
          <div class="row">
            <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              :imgs="arr"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
            ></slide-verify>
          </div>
          <div class="row">
            <input
              type="text"
              placeholder="请输入短信验证码"
              class="ipt"
              v-model="code"
            />
            <button class="codebtn" @click="getCode" v-show="!isShowCount">
              获取验证码
            </button>
            <button class="codebtn" v-show="isShowCount">{{ count }}</button>
          </div>
          <div class="row">
            <button class="ipt" @click="submitFn">登录</button>
          </div>
        </div>
        <div class="qrLogin" id="weixin" v-show="!isShowContent"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapMutations, mapActions } from "vuex";
import { validateTelephoneNumber } from "../utils";
import { sendSMSAPI, PhoneLoginAPI, bindingAPI } from "../request/Api";

export default {
  data() {
    return {
      isShowContent: true,
      msg: "向右滑动",
      arr: [
        require("../assets/img/integral-01.9386d4bf.png"),
        require("../assets/img/integral-02.150d92a1.png"),
      ],
      phoneNumber: "",
      count: 5,
      isShowCount: false,
      code: "",
    };
  },
  methods: {
    ...mapMutations({
      changeIsShowModal: "showModal/changeIsShowModal",
      changeIsLogined: "loginStatus/changeIsLogined",
    }),
    ...mapActions({
      asyncChangeIsShowToast: "showToast/asyncChangeIsShowToast",
      asyncUpdateUserInfo: "userInfo/asyncUpdateUserInfo",
    }),
    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },
    // 封装手机号和滑块验证
    toVerify() {
      // 验证手机号
      if (!validateTelephoneNumber(this.phoneNumber)) {
        // return alert("请输入正确手机号");
        this.asyncChangeIsShowToast({
          isShow: true,
          msg: "请输入正确手机号",
          type: "warning",
        });
        return;
      }
      // 验证滑块
      if (this.msg === "再试一次" || this.msg === "向右滑动") {
        // return alert("请正确滑动拼图");
        this.asyncChangeIsShowToast({
          isShow: true,
          msg: "请正确滑动拼图",
          type: "warning",
        });
        return;
      }
      return true;
    },

    // 获取验证码
    async getCode() {
      let flag = this.toVerify();
      if (!flag) return;
      // 发送请求
      let res = await sendSMSAPI({
        phone: this.phoneNumber.trim(),
      });
      if (res.data.code == 0) {
        alert("短信发送成功");
        // 倒计时
        this.isShowCount = true;
        var timer = setInterval(() => {
          this.count--;
          if (this.count <= 0) {
            this.count = 5;
            clearInterval(timer);
            this.isShowCount = false;
          }
        }, 1000);
      }
    },

    // 获取微信二维码
    showQR() {
      this.isShowContent = false;
      let _this = this;
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://127.0.0.1:8080" + _this.$route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLA0KLmltcG93ZXJCb3ggLmluZm8gew0KICAgIGRpc3BsYXk6IG5vbmU7DQp9",
      });
    },

    // 登录按钮
    async submitFn() {
      if (!this.toVerify()) return;
      // 验证验证码
      if (!this.code.trim()) return alert("请输入正确的验证码");

      //点击登录时分场景，有uuid时 发起手机微信关联请求， 否则发起手机登录请求
      let uuid = localStorage.getItem("uuid");
      let res = null;
      if (uuid) {
        res = await bindingAPI({
          phone: this.phoneNumber,
          verifyCode: this.code,
          uuid,
        });
      } else {
        res = await PhoneLoginAPI({
          phone: this.phoneNumber,
          verifyCode: this.code,
        });
      }
      if (res.data.code == 0) {
        this.asyncChangeIsShowToast({
          isShow: true,
          msg: "登陆成功",
          type: "success",
        });
        // 保存token值到localStorage
        localStorage.setItem("x-auth-token", res.data["x-auth-token"]);
        // 隐藏登录模态窗口
        this.changeIsShowModal(false);
        // 登录状态的切换
        this.changeIsLogined(true);
        // 删除uuid
        if (uuid) {
          localStorage.removeItem("uuid");
        }
        //清除浏览器地址栏上的code
        this.$router.push(this.$route.path);
        // 登陆成功获取用户信息
        this.asyncUpdateUserInfo();
      } else {
        // 登录不成功提示
        this.asyncChangeIsShowToast({
          isShow: true,
          msg: "登陆不成功",
          type: "danger",
        });
      }
    },
  },
};
</script>

<style lang="less" scoped>
.modal {
  position: fixed;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  .mask {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }
  .loginbox {
    position: absolute;
    inset: 0;
    margin: auto;
    width: 555px;
    height: 423px;
    background: url("../assets/img/login-box-bg.png");
    .close {
      position: absolute;
      width: 22px;
      height: 22px;
      top: 10px;
      right: 60px;
    }
    .nav {
      text-align: center;
      padding-top: 20px;
      a {
        text-decoration: none;
        color: #ccc;
        &.active {
          color: #333;
          font-weight: bold;
        }
      }
    }
    .content {
      width: 355px;
      margin: 20px auto 0;
      height: 200px;
      .row {
        display: flex;
        align-items: center;
        .ipt {
          flex: 1;
          height: 50px;
          margin: 10px 0;
          padding-left: 20px;
        }
        .codebtn {
          width: 100px;
          height: 56px;
          margin-left: 10px;
        }
        button {
          background-color: #12358d;
          color: #fff;
        }
      }
      .qrLogin {
        text-align: center;
      }
    }
  }
}

/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>